<?php
/**
 * Created by PhpStorm.
 * User: gqn
 * Date: 2016/3/4
 * Time: 16:02
 */

namespace Api\Controller;

use Think\Log;

Class CommentController extends BaseController {


    /**
     * 评价
     */
    public function index(){
        //解决跨域
        echoHeader();
        //用户id
        $user_id = I('post.user_id');
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        //师傅id
        $worker_user_id = I('post.worker_user_id');
        if($worker_user_id) {
            $data = self::checkUserIsExist($worker_user_id);
            if (!$data['user']) {
                $this->ajaxReturn($data);
            }
        }
        //订单id
        $order_id = I('post.order_id');

        //1用户对师傅评价 2用户对师傅的追评 3师傅对用户的评价
        $status = I('post.status','');
        if(empty($status)){
            $array = array('err_code'=>403,'err_msg'=>'参数缺失');
            $this->ajaxReturn($array);
        }
        if($status=='1') {
            $info['user_id'] = $user_id;
            $info['worker_user_id'] = $worker_user_id;
            $info['speed'] = I('post.speed'); //速度
            $info['attitude'] = I('post.attitude');//态度
            $info['skill'] = I('post.skill');//技术
            $info['health'] = I('post.health');//卫生
            $info['charge'] = I('post.charge');//收费
            $info['order_id'] = $order_id; //订单id
            $info['content'] = I('post.content',''); //评论内容
            $info['add_time'] = time();
            $ins = M('comment_master')->where("user_id = $user_id and order_id = $order_id")->find();
            if (!empty($ins)) {
                $array = array('err_code' => 404, 'err_msg' => '您已评论过该订单！');
                $this->ajaxReturn($array);
            }
            $data = M('comment_master')->add($info);
            if ($data && empty($ins)) {
                $total = $info['speed'] + $info['attitude'] + $info['skill'] + $info['health'] + $info['charge'];
                $this->pingjia($user_id,$info['order_id'], $total);

                //更改订单用户已评价状态
                $saveOrderStatus['user_comment'] = '1';
                $whereOrder['repair_order_num_alias'] = array('eq',$order_id);
                M('repair_order')->where($whereOrder)->save($saveOrderStatus);
                //更新师傅平均星级
                //完成订单数
                $map['status'] = array('in','8,9,10,11,12,13,14');
                $map['user_comment'] = array('eq',1);
                $map['worker_user_id'] = array('eq',$worker_user_id);
                $counts = M('repair_order')->where($map)->count();
                //总共星级
                $totalStar = M()->query("select (sum(speed)+sum(attitude)+sum(skill)+sum(health)+sum(charge)) as sum from zsf_comment_master where worker_user_id = $worker_user_id group by worker_user_id");
                $grade = $totalStar[0]['sum']/($counts*6);

                $gradeWhe['user_id'] = array('eq',$worker_user_id);
                $gradeSave['grade'] = $grade;
                M('user_real_info')->where($gradeWhe)->save($gradeSave);
                $array = array('err_code' => 200, 'err_msg' => '评论成功！');
                $this->ajaxReturn($array);
            }else{
                $array = array('err_code' => 405, 'err_msg' => '评论失败！');
                $this->ajaxReturn($array);
            }

        }elseif($status=='2'){
            $data['order_id'] = array('eq',$order_id);
            $data['user_id'] = array('eq',$user_id);
            $ins = M('comment_master')->field('append_content')->where($data)->find();
            if(!empty($ins['append_content'])){
                $array = array('err_code' => 404, 'err_msg' => '您已追评过该订单！');
                $this->ajaxReturn($array);
            }
            $info['append_content'] = trim(I('post.content',''));
            if(empty($info['append_content'])){
                $array = array('err_code' => 406, 'err_msg' => '追评内容不能为空！');
                $this->ajaxReturn($array);
            }
            $data = M('comment_master')->where($data)->save($info);
            if($data){
                $array = array('err_code' => 200, 'err_msg' => '追评成功！');
                $this->ajaxReturn($array);
            }

        }elseif($status=='3'){

            $mas = M('repair_order')->field('user_id')->where("repair_order_num_alias = $order_id and worker_user_id = $user_id")->find();
            $ins = M('comment_user')->where("worker_user_id = $user_id and order_id = $order_id")->find();
            if (!empty($ins)) {
                $array = array('err_code' => 404, 'err_msg' => '您已评论过该订单！');
                $this->ajaxReturn($array);
            }
            $data['user_id'] = $mas['user_id'];
            $data['worker_user_id'] =$user_id ;
            $data['order_id'] = $order_id;
            $data['point'] = I('post.point');
            $data['content'] = I('post.content','');
            $data['add_time'] = time();
            $info = M('comment_user')->add($data);

            if($info){
                //更改订单师傅已评价状态
                $saveOrderStatus['master_comment'] = '1';
                $whereOrder['repair_order_num_alias'] = array('eq',$order_id);
                M('repair_order')->where($whereOrder)->save($saveOrderStatus);

                $array = array('err_code' => 200, 'err_msg' => '评论成功！');
                $this->ajaxReturn($array);
            }else{
                $array = array('err_code' => 405, 'err_msg' => '评论失败！');
                $this->ajaxReturn($array);
            }
        }
    }

    /**
     * 查看评价列表
     */
    public function check(){
        //解决跨域
        echoHeader();
        //用户id
        $user_id = I('post.user_id');
        $data = self::checkUserIsExist($user_id);
        if(!$data['user']){
            $this->ajaxReturn($data);
        }
        $role = $data[user][identity];

        //1用户给师傅的评价 2师傅给用户的评价
        $type = I('post.role',1);

        //用户端
        if($role==1){
            $nickname = 'user_id';
        }elseif($role==2){
            $nickname = 'worker_user_id';
        }
        if($type==1){
            $data = M('comment_master')->where("$nickname = $user_id")->select();
            if($data){
                foreach($data as $k=>$v){
                    $data[$k]['add_time'] = date('Y-m-d H:i:s',$data[$k]['add_time']);
                    $name = M()->table('zsf_repair_order rep')->field('wor.id_name,usr.user_name')
                            ->join('LEFT JOIN zsf_user_real_info wor on rep.worker_user_id = wor.user_id')
                            ->join("LEFT JOIN zsf_user usr on rep.user_id = usr.user_id")
                            ->where('rep.repair_order_num_alias = '.$data[$k][order_id])->find();
                    $data[$k]['worker'] = $name['id_name'];
                    $data[$k]['user'] = $name['user_name'];
                    $data[$k]['star'] = $data[$k]['speed']+$data[$k]['attitude']+$data[$k]['skill']+$data[$k]['health']+$data[$k]['charge'];
                }
            }
        }else{
            $data = M('comment_user')->where("$nickname = $user_id")->select();
            if($data){
                foreach($data as $k=>$v){
                    $data[$k]['add_time'] = date('Y-m-d H:i:s',$data[$k]['add_time']);
                    $name = M()->table('zsf_repair_order rep')->field('wor.id_name,usr.user_name')
                        ->join('LEFT JOIN zsf_user_real_info wor on rep.worker_user_id = wor.user_id')
                        ->join("LEFT JOIN zsf_user usr on rep.user_id = usr.user_id")
                        ->where('rep.repair_order_num_alias = '.$data[$k][order_id])->find();
                    $data[$k]['worker'] = $name['id_name'];
                    $data[$k]['user'] = $name['user_name'];
                }
            }
        }
        if(!$data){
            $array = array('err_code'=>403,'err_msg'=>'暂无评价');
            $this->ajaxReturn($array);
        }
        $array = array('err_code'=>200,'err_msg'=>$data);
        $this->ajaxReturn($array);

    }


    /**
     * 评价体系
     */
    private function pingjia($user_id,$order_id,$total){
        $owhere['repair_order_num_alias']=$order_id;
        $order=M('repair_order')->where($owhere)->find();
        $pingjia=M('pingjia')->where('status=2')->find();
        $m=empty($order['fixed_price'])?$order['total']:$order['fixed_price'];
        $p_m=$pingjia_money=M('pingjia')->where('id=4')->find();
        file_put_contents('/tmp/test.txt',"评价开始=================$m"."\r\n",FILE_APPEND);

        $data['money']=0;
        if($total>20){
            $money=(($total-20)*$m)/$p_m['money'];

            $money=$money>5?5:$money;

            $wh['user_id']=$order['worker_user_id'];
            $user=M('user')->where($wh)->find();
            //师傅每天封底20元，检查还有没有奖励金额

            $money=$user['rewards_money']>5?$money:$user['rewards_money'];
            $rewards_money=$user['rewards_money']-$money;
            //更改每天奖励金额
            $save['rewards_money']=$rewards_money<=0?0:$rewards_money;
            M('user')->where($wh)->save($save);
            $data['money']=$money;
            $is_plus=1;
          //  file_put_contents('/tmp/test.txt',"评价分数+：$rewards_money"."\r\n",FILE_APPEND);
        }elseif($total<20){
            $constant=(int)$pingjia['constant'];
            $variable=(int)$pingjia['variable'];
            $money=$m*(($constant-$variable*$total)/100);
            $data['money']=$money;
            $is_plus=0;
         //   file_put_contents('/tmp/test.txt',"评价分数-：$total"."\r\n",FILE_APPEND);
        }
        //file_put_contents('/tmp/test.txt',"1111111");
        //\Think\Log::write("订单号：$order_id ；评价分数：$total；奖励：".$data['money']."\r\n");
        //把金额存入zsf_rewards_money表
        $data['order_id']=$order_id;
        $data['total']=$total;

        $mdata['user_id']=$order['worker_user_id'];
        $mdata['type']=4;
        $mdata['flag']=5;
        $mdata['protocol_id']=$order['protocol_id'];
        $mdata['total']= $data['money'];
        $mdata['order_id']=$order['repair_order_id'];
        $mdata['is_plus']=$is_plus;
        $mdata['balance']=1;
        $mdata['remark']="评价佣金奖罚,锁定期后处理";
        $mdata['add_time']=time();
     //   file_put_contents('/tmp/test.txt',var_export($mdata)."\r\n",FILE_APPEND);
        M('money_history')->add($mdata);
    }

    /**
     * 获取评价
     */

    public function getInfo(){
        $info = array();
        $comment = M('Comment')->select();
        foreach($comment as $k=>$v){
            if($v['p_id']== 0){
                $info[$k][] = $v['c_name'];
                foreach($comment as $s=>$c){
                    if($v['id']==$c['p_id']){
                        $info[$k][] = $c['c_name'];
                    }
                }
            }
        }
        sort($info);
        $this->ajaxReturn($info);
    }
}